﻿using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
namespace ImageServer.Controllers
{
    [ApiController]
    [Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    public class ImageController:ControllerBase
    {
        private readonly string _imagesFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
        //要求请求头中包含 JWT Token
        [HttpPost("upload")]
        [Authorize]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            // 检查文件是否为空
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }
            // 检查文件类型是否为 PNG
            if (file.ContentType != "image/png")
            {
                return BadRequest("Only PNG files are allowed.");
            }
            // 获取当前用户 ID
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null)
            {
                return Unauthorized("User ID not found.");
            }
            // 生成唯一的文件名
            string userId = userIdClaim.Value;
            string uniqueFileName = $"{userId}.png";
            var filePath = Path.Combine(_imagesFolderPath, uniqueFileName);
            // 确保目录存在
            if (!Directory.Exists(_imagesFolderPath))
            {
                Directory.CreateDirectory(_imagesFolderPath);
            }

            // 保存文件到服务器,并删除原有文件
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            // 返回成功响应
            return Ok(new { message = "File uploaded successfully.", fileUrl = $"/upload/{uniqueFileName}" });
        }
        [HttpGet("{name}")]
        public IActionResult GetImage(string name)
        {
            // 构建图片的完整路径
            string imagePath = Path.Combine(_imagesFolderPath, $"{name}.png");
            // 检查图片是否存在
            if (System.IO.File.Exists(imagePath))
            {
                // 返回图片文件
                return PhysicalFile(imagePath, "image/png");
            }
            else
            {
                // 返回404 Not Found
                return NotFound();
            }
        }

    }
}
